package cn.dakaqi.services.impl;

import cn.dakaqi.dao.PassportApplyDao;
import cn.dakaqi.entities.BaseAddress;
import cn.dakaqi.entities.PassportApply;
import cn.dakaqi.entities.PassportApplyOrder;
import cn.dakaqi.entities.PassportAppointmentDate;
import cn.dakaqi.services.*;
import cn.dakaqi.utils.Clock;
import cn.dakaqi.utils.exception.ServiceRuntimeException;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Copyright: Copyright (c)2016
 * Company: 志愿者打卡器(www.dakaqi.cn)
 * 类名称: PassportApplyServiceImpl <br>
 * 类描述: <br>
 *
 * @author: ChunYang.Zhang
 * @since: 2016/10/20 9:20
 * @version: 1.0.0
 */
@Slf4j
@Transactional
@Component(value = "passportApplyService")
public class PassportApplyServiceImpl implements PassportApplyService
{
    @Autowired
    PassportApplyDao passportApplyDao;
    @Autowired
    PassportApplyOrderService passportApplyOrderService;
    @Autowired
    BaseAddressService baseAddressService;
    @Autowired
    PassportAppointmentDateService passportAppointmentDateService;
    @Autowired
    PassportSeqService passportSeqService;

    @Override
    public void  save(PassportApply passportApply) throws ServiceRuntimeException
    {
        synchronized(this)
        {
            passportApplyDao.save(passportApply);
            log.info(passportApply.toString());
            PassportApplyOrder passportApplyOrder = new PassportApplyOrder();
            passportApplyOrder.setStatus(PassportApplyOrder.STAUTS_WAITE);
            passportApplyOrder.setCreateTime(Clock.DEFAULT.getCurrentDate());
            passportApplyOrder.setHead(passportApply.getHead());


            //团体预约
            if(passportApply.getAppointmenDate().equals("0000-00-00"))
            {
                passportApplyOrder.setAppointmenDate(passportApply.getAppointmenDate());
                passportApplyOrder.setAppointmentTime(passportApply.getAppointmentTime());
                passportApplyOrder.setValidityDate("0000-00-00");
            }
            else
            {
                //检查当前基地是否有还可以预约,当天是否有可以预约名额
                PassportAppointmentDate pad = passportAppointmentDateService.findByDayAndTime(passportApply.getBassAddressId(), passportApply.getAppointmenDate(), passportApply.getAppointmentTime());
                if(null != pad && pad.getNum()>0 && pad.getStatus() == PassportAppointmentDate.STATUS_YES)
                {
                    passportApplyOrder.setAppointmenDate(passportApply.getAppointmenDate());
                    passportApplyOrder.setAppointmentTime(passportApply.getAppointmentTime());
                    this.passportAppointmentDateService.updateNum(pad);
                }
                else
                {
//                String day = DateUtil.getAfterDay("",11);
//                String content = "请与"+day+"后的工作时间至预约地址领取";
//                passportApplyOrder.setAppointmenDate(content);
//                passportApplyOrder.setAppointmentTime("");

//                    String day = DateUtil.getAfterDay("",11);
//                    passportApplyOrder.setAppointmenDate(day);
//                    passportApplyOrder.setAppointmentTime("");

                    passportApplyOrder.setAppointmenDate(passportApply.getAppointmenDate());
                    passportApplyOrder.setAppointmentTime(passportApply.getAppointmentTime());

                }
            }


            passportApplyOrder.setBassAddressId(passportApply.getBassAddressId());
            passportApplyOrder.setCardNO(passportApply.getCardNO());
            passportApplyOrder.setCardType(passportApply.getCardType());
            passportApplyOrder.setNote(passportApply.getNote());
            passportApplyOrder.setMobile(passportApply.getMobile());
            passportApplyOrder.setName(passportApply.getName());
            passportApplyOrder.setSex(passportApply.getSex());

            //生成订单号
            passportApplyOrder.setNum(PassportApplyOrder.createNum());
            passportApplyOrder.setOldNum(passportApplyOrder.getNum());


            //查询基地信息
            BaseAddress baseAddress = this.baseAddressService.findOne(passportApply.getBassAddressId());
            passportApplyOrder.setSignAddress(baseAddress.getPutUpAddr());
            passportApplyOrder.setSignUnti(baseAddress.getName());
            passportApplyOrder.setSignDate("");
            //团体预约
            if(passportApply.getAppointmenDate().equals("0000-00-00"))
            {
                passportApplyOrder.setValidityDate("0000-00-00");
            }
            else
            {
                String temp[] = passportApply.getAppointmenDate().split("-");
                passportApplyOrder.setValidityDate((Integer.parseInt(temp[0]) +1) +"-" +temp[1] +"-" +temp[2]);
            }
            passportApplyOrder.setBirthday(passportApply.getBirthday());
            passportApplyOrder.setApplyType(passportApply.getApplyType());
            passportApplyOrder.setApplyCase(passportApply.getApplyCase());
            passportApplyOrder.setContactAddress(passportApply.getContactAddress());
            passportApplyOrder.setContactName(passportApply.getContactName());
            passportApplyOrder.setContactPhone(passportApply.getContactPhone());

            passportApplyOrder.setGuardianCardNo(passportApply.getGuardianCardNo());
            passportApplyOrder.setGuardianName(passportApply.getGuardianName());
            passportApplyOrder.setGuardianSex(passportApply.getGuardianSex());
            passportApplyOrder.setGuardianRelation(passportApply.getGuardianRelation());
            passportApplyOrder.setGuardianPhone(passportApply.getGuardianPhone());
            passportApplyOrder.setGuardianCardType(passportApply.getGuardianCardType());
            passportApplyOrder.setGuardianUnit(passportApply.getGuardianUnit());
            passportApplyOrder.setGuardianUnitCode(passportApply.getGuardianUnitCode());
            PassportApplyOrder tempOrder = this.passportApplyOrderService.findAllCardNO(passportApplyOrder.getCardNO());
            if(passportApplyOrder.getApplyType() == 10)
            {
                passportApplyOrder.setDemo("");
                //公益护照编号
                //PassportApplyOrder lastOrder = this.passportApplyOrderService.findLastOrder();
                //passportApplyOrder.setPassportNO(PassportApplyOrder.portNO(passportApply.getCardNO()));
                passportApplyOrder.setPassportNO(this.generatorPassportNo("上海市"));
            }
            else if(passportApplyOrder.getApplyType() == 20 && null != tempOrder)
            {

                passportApplyOrder.setDemo("本护照根据第xxxx号护照换发");
                //公益护照编号
                //PassportApplyOrder lastOrder = this.passportApplyOrderService.findLastOrder();
                tempOrder = this.passportApplyOrderService.findAllCardNO(passportApplyOrder.getCardNO());
                passportApplyOrder.setPassportNO(tempOrder.getPassportNO());

            }
            else if(passportApplyOrder.getApplyType() == 30 && null != tempOrder)
            {
                passportApplyOrder.setDemo("本护照根据第xxxx号护照补发");
                //公益护照编号
                //PassportApplyOrder lastOrder = this.passportApplyOrderService.findLastOrder();
                tempOrder = this.passportApplyOrderService.findAllCardNO(passportApplyOrder.getCardNO());
                passportApplyOrder.setPassportNO(tempOrder.getPassportNO());
            }

            passportApplyOrder.setOrderStatus(PassportApplyOrder.ORDER_STAUTS_NORMAL);
            passportApplyOrder.setApplyForm(PassportApplyOrder.FROM_ONLINE);
            log.info(passportApplyOrder.toString());
            passportApplyOrderService.save(passportApplyOrder);
            log.info(passportApplyOrder.toString());
            if(null != tempOrder)
            {
                tempOrder.setStatus(PassportApplyOrder.STAUTS_LOGOUT);
                this.passportApplyOrderService.update(tempOrder);
            }
        }
    }

    @Override
    public PassportApply findByCardNO(String cardNO) throws ServiceRuntimeException
    {
        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("cardNO", new SearchFilter("cardNO", SearchFilter.Operator.EQ, cardNO));
        Specification<PassportApply> spec = DynamicSpecifications.bySearchFilter(filters.values(), PassportApply.class);
        List<PassportApply> list = this.passportApplyDao.findAll(spec);
        if(null != list && list.size()>0)
            return list.get(0);
        return null;
    }

    @Override
    public PassportApply findOne(Long id) throws ServiceRuntimeException
    {
        return this.passportApplyDao.findOne(id);
    }

    //生成志愿者CODE
    private synchronized String generatorPassportNo(final String provideName)
    {
         int value = passportSeqService.updatePassportSeqByName(provideName);

        String seq = String.format("%09d", value);
        log.info("generatorPassportNo------------>"+seq);

        String pattern  = "(\\d)\\1{2}$";
        // 创建 Pattern 对象
        Pattern r = Pattern.compile(pattern);
        // 现在创建 matcher 对象
        Matcher m = r.matcher(seq);
        if(m.find())
        {
            value = passportSeqService.updatePassportSeqByName(provideName);
             seq = String.format("%09d", value);
            log.info("generatorPassportNo------------>"+seq);
        }

        return   "310000001"+seq;
    }

}
